<?php

namespace App\Console\Commands;

use App\Models\MeterType;
use function GuzzleHttp\Psr7\str;
use Illuminate\Console\Command;
use Laravel\File;
use Prophecy\Doubler\Generator\TypeHintReference;
use function Zend\Diactoros\normalizeUploadedFiles;

class AddSimpleFeeType extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'add:simpleFeeType {type_name} {chi_name} {--hasMeter}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'a tool command to add simple fee type refer to waterFeeType. usage sample eg.1 [ add:hotWater 热水 ] eg.2 [add:hotWater 热水 --hasMeter]';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //1. create fee type l5-repository entity
        $feeType = $this->argument('type_name');
        $hasMeter = $this->option('hasMeter');
        $feeType = camel_case($feeType);

        $feeType = ends_with($feeType,'FeeType')?$feeType:$feeType.'FeeType';//xxYyFeeType
        $feeTypeCn = $this->argument('chi_name');
        $feeTypeCn = str_ends_with($feeTypeCn,'费')?$feeTypeCn:$feeTypeCn.'费';

        $snakeType = snake_case($feeType);
        $snakeTypeId = $snakeType.'_id';
        $camelType = camel_case($feeType);//xxYy
        $camelTypes = str_plural($camelType);//XxYys
        $snakeTypes = snake_case($camelTypes);
        $routeType = kebab_case($camelTypes);//xx-yys

        $pascalType = studly_case($feeType);//XxYy(pascal style)
        $pascalTypes = str_plural($pascalType);//XxYys
        $new_model = app_path("Models/$pascalType.php");
        if(!file_exists($new_model)){
            @$this->call("make:entity",['name'=>$feeType]);
        }
        $w_model = app_path("Models/WaterFeeType.php");
        $this->replaceContent($w_model,$new_model,['WaterFeeType'=>$pascalType]);
        $new_ctrl = app_path("Http/Controllers/$pascalTypes"."Controller.php");
        $w_ctrl = app_path("Http/Controllers/WaterFeeTypesController.php");
        $this->replaceContent($w_ctrl,$new_ctrl,['WaterFeeType'=>$pascalType,'waterFeeType'=>$camelType]);

        $files = glob(app_path('Http/Requests/*.php'));
        foreach ($files as $file){
            $this->replaceFileContent($file,['return false'=>'return true']);
        }

        //1.1 patch migration file
        $files = glob(database_path('migrations/').'*.php');
        $name="create_$snakeTypes".'_table';
        foreach ($files as $file){
            if(str_contains($file,$name)){
                $new_migration = $file;
                break;
            }
        }

        $insert =<<<'EOT'
			$table->string('name');
			$table->decimal('fee');
            $table->string('compute_unit')->comment('每间或每度');
            $table->string('remark')->nullable();
EOT;
        $this->insert($new_migration,18,$insert);

        //1.2 copy and patch feeType view
        if($hasMeter){
            $src_dir = resource_path("views/waterFeeTypes");
        }else{
            $src_dir = resource_path("views/manageFeeTypes");
        }

        $dist_dir = resource_path("views/$camelTypes");
        if(!file_exists($dist_dir)){
            $this->copydir($src_dir,$dist_dir);
            $views = [$dist_dir.'/create.blade.php',$dist_dir.'/index.blade.php',$dist_dir.'/edit.blade.php'];
            foreach ($views as $view){
                if($hasMeter){
                    $this->replaceViewsOnWaterFee($view, $camelType, $pascalType, $feeTypeCn, $routeType);
                }else{
                    $this->replaceViewsOnManageFee($view, $camelType, $pascalType, $feeTypeCn, $routeType);
                }

            }
        }


        //1.3 insert route
        $route_file = base_path('routes/web.php');
        $insert = "Route::resource('$routeType', '$pascalTypes"."Controller');";
        if($this->indexOfLine($route_file,$insert)==-1){
            $this->info("going to insert route to $route_file");
            $idx = $this->indexOfLine($route_file,"Route::resource('water-fee-types', 'WaterFeeTypesController');");
            $this->insert($route_file,$idx,$insert,false);
        }



        //1.4 insert to layout
        $layout_file = resource_path('views/layouts/x-admin.blade.php');
        $feeClsCn = $feeTypeCn.'类别';
        $insert =<<<EOF
                                <li>
                                    <a onclick="xadmin.add_tab('$feeClsCn','{{route('$routeType.index')}}')">
                                        <i class="iconfont">&#xe6a7;</i>
                                        <cite>$feeClsCn</cite></a>
                                </li>
EOF;

        if($this->indexOfLine($layout_file,"<cite>$feeClsCn</cite></a>")==-1){
            $idx = $this->indexOfLine($layout_file,'<cite>水费类别</cite></a>')+1;
            $this->insert($layout_file,$idx,$insert,false);

        }


        //1.5 insert to DormType
        //1.5.1 model
        $model_file = app_path('Models/DormType.php');
        $insert="'$snakeTypeId',";
        if($this->indexOfLine($model_file,$insert)==-1){
            $this->insert($model_file,29,$insert."\n",false);
        }

        $line = "public function $camelType()";
        if($this->indexOfLine($model_file,$line)==-1){
            $insert = "\n$line\n{return ".'$this->belongsTo('."$pascalType::class);\n}";
            $index = $this->indexOfLine($model_file,'public function waterFeeType()')-1;
            $this->insert($model_file,$index,$insert,false);
        }


        //1.5.2 migration file
        $this->makeAddColumnMigration('dorm_types',$snakeTypeId,'unsignedInteger');


        //1.5.3 controller
        $ctrl_file = app_path('Http/Controllers/DormTypesController.php');
        $insert = "use App\\Models\\$pascalType;";
        if($this->indexOfLine($ctrl_file,$insert)==-1){
            $this->insert($ctrl_file,8,$insert,false);
        }
        $insert = '$'."$camelTypes = $pascalType::all()->pluck('name','id');";
        if($this->indexOfLine($ctrl_file,$insert)==-1){
            $ms = $this->matchLines($ctrl_file,"return view('dormTypes.create'");
            foreach ($ms as $i=>$line) {
                $line = str_replace("'waterFeeTypes',","'waterFeeTypes',"."'$camelTypes',",$line);
                $this->replaceLine($ctrl_file,$i,$line);
                $this->insert($ctrl_file,$i-3,$insert,false);
            }

            $ms = $this->matchLines($ctrl_file,"return view('dormTypes.edit'");
            foreach ($ms as $i=>$line) {
                $line = str_replace("'waterFeeTypes',","'waterFeeTypes',"."'$camelTypes',",$line);
                $this->replaceLine($ctrl_file,$i,$line);
                $this->insert($ctrl_file,$i-3,$insert,false);
            }

            $ms = $this->matchLines($ctrl_file,'$dormTypes = $this->repository->with');
            foreach ($ms as $i=>$line){
                $line = str_replace("'waterFeeTypes',","'waterFeeTypes',"."'$camelTypes',",$line);
                $this->replaceLine($ctrl_file,$i,$line);
            }
        }


        //1.5.4 views of dormTypes
        //create view
        $create_view = resource_path('views/dormTypes/create.blade.php');
        $insert_ref = <<<'EOF'
            <div class="layui-form-item">
                <label class="layui-form-label">
                    水费类型
                </label>
                <div class="layui-input-block">
                    <select name="water_fee_type_id">
                        <option value="">无</option>
                        @foreach($waterFeeTypes as $k=>$v)
                            <option value="{{$k}}">{{$v}}</option>
                        @endforeach
                    </select>
                </div>
            </div>
EOF;
        $ref_line='@foreach($waterFeeTypes as $k=>$v)';
        $replacements = ['水表'=>$name,'waterFeeType'=>$camelType,'水费类型'=>$feeClsCn,'water_fee_type'=>$snakeType];
        $this->insertFileWithCheck($create_view,$insert_ref,$replacements,5, $ref_line);

        //edit view
        $edit_view = resource_path('views/dormTypes/edit.blade.php');
        $insert_ref = <<<'EOF'
            <div class="layui-form-item">
                <label class="layui-form-label">
                    水费类型
                </label>
                <div class="layui-input-block">
                    <select name="water_fee_type_id">
                        <option value="" {{$dormType->water_fee_type_id?'':'selected'}}>无</option>
                        @foreach($waterFeeTypes as $k=>$v)
                            <option value="{{$k}}" {{$dormType->water_fee_type_id==$k?'selected':''}}>{{$v}}</option>
                        @endforeach
                    </select>
                </div>
            </div>
EOF;
        $ref_line='@foreach($waterFeeTypes as $k=>$v)';
        $replacements = ['水表'=>$name,'waterFeeType'=>$camelType,'水费类型'=>$feeClsCn,'water_fee_type'=>$snakeType];
        $check_line = '@foreach($'.$camelTypes.' as $k=>$v)';
        $this->insertFileWithCheck($edit_view,$insert_ref,$replacements,5, $ref_line,$check_line);

        //index view
        $index_view = resource_path('views/dormTypes/index.blade.php');
        $insert_ref = <<<EOF
                , {
                    field: 'waterFeeType.name', title: '水费类型', width: 100, templet: function (d) {
                        return d.water_fee_type?.name||'';
                    }
                }
EOF;

        $ref_line ="return d.water_fee_type.name;";
        $replacements = ['waterFeeType'=>$camelType,'水费类型'=>$feeClsCn,'water_fee_type'=>$snakeType];
        $this->insertFileWithCheck($index_view,$insert_ref,$replacements,2, $ref_line);

        //1.6 insert model lang
        $mode_lang_file = resource_path('lang/zh-CN/model.php');
        $insert = "\"$routeType\" => \"$feeClsCn\",";
        if($this->indexOfLine($mode_lang_file,$insert)==-1){
            $this->insert($mode_lang_file,18,$insert,false);
        }


        //1.7 meter type
        $meter=null;
        if($hasMeter){
            $meterCode = snake_case(str_replace('FeeType','Meter',$camelType));
            $pascalMeterCode = studly_case($meterCode);
            $abbr = substr($meterCode,0,1);
            $name = str_replace('费','表',$feeTypeCn);
            $meter = MeterType::updateOrCreate(['code'=>$meterCode],['code'=>$meterCode,'abbr'=>$abbr,'name'=>$name,'unit'=>'计量单位','unit_price'=>0]);

            //1.7.1 dorm model file
            $dorm_model_file = app_path('Models/Dorm.php');
            $ms = $this->matchLines($dorm_model_file,"public function active$pascalMeterCode()");
            if(count($ms)==0){
                $insert_ref = <<<'EOF'
    public function activeWaterMeter(){
        return $this->hasOne(DormMeter::class)->where('meter_type_id',METER_ID)->where('active',1);
    }
EOF;
                $ref_line = 'public function activeWaterMeter(){';
                $this->insertFileWithCheck($dorm_model_file,$insert_ref,['METER_ID'=>$meter->id,'WaterMeter'=>$pascalMeterCode],2,$ref_line);
            }

            //1.7.2 dorm transformer file
            $dorm_tran_file = app_path('Transformers/DormTransformer.php');
            $insert_ref = '\'water_meter_id\'=>optional($model->activeWaterMeter)->id,';
            $this->insertFileWithCheck($dorm_tran_file,$insert_ref,['water_meter'=>$meterCode,'WaterMeter'=>$pascalMeterCode]);

            //1.7.3 dorm index view
            $dorm_index_view = resource_path('views/dorms/index.blade.php');
            $insert_ref =<<<EOF
    @{{# if(d.water_meter_id) { }}
    <a class="layui-btn layui-btn-xs" lay-event="replace_water_meter">更换水表</a>
    @{{# }else{ }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="set_water_meter">设置水表</a>
    @{{# } }}
EOF;
            $ref_line='<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="set_water_meter">设置水表</a>';
            $this->insertFileWithCheck($dorm_index_view,$insert_ref,['water_meter'=>$meterCode,'水表'=>$name],1,$ref_line);


            $insert_ref=<<<'EOF'
                case 'set_water_meter':
                    url += `&action=set&meter_type=METER_ID`
                    title = `设置 ${dorm_info} 水表`;
                    break;
                case 'replace_water_meter':
                    url += `&action=replace&meter_type=METER_ID`
                    title = `更换 ${dorm_info} 水表`;
                    break;
EOF;


            $ref_line = "case 'replace_$meterCode':";
            $this->insertFileWithCheck($dorm_index_view,$insert_ref,['水表'=>$name,'water_meter'=>$meterCode,'METER_ID'=>$meter->id],3,$ref_line);


        }

        //1.8 staffPeriodFee
        //1.8.1 migration file
        $col = str_replace('_type','',$snakeType);
        $this->makeAddColumnMigration('staff_period_fees',$col,'decimal');

        //1.8.2 model file
        $spf_model_file = app_path('Models/StaffPeriodFee.php');
        $ms = $this->matchLines($spf_model_file,'protected $fillable =');
        foreach ($ms as $idx=>$line) {
            if(!str_contains($line,$col)){
                $line=str_replace("'water_fee',","'water_fee','$col',",$line);
                $this->replaceLine($spf_model_file,$idx,$line);
            }
        }
        $insert_ref = 'if($this->water_fee)$total+=$this->water_fee;';
        $this->insertFileWithCheck($spf_model_file,$insert_ref, ['water_fee'=>$col]);

        //1.8.3 model view
        $spf_index_view = resource_path('views/staffPeriodFees/index.blade.php');
        $insert_ref = ", {field: 'water_fee', title: '水费', width: 90, sort: true}";
        $this->insertFileWithCheck($spf_index_view,$insert_ref,['water_fee'=>$col,'水费'=>$feeTypeCn]);

        //1.8.4 tranformer file
        $trans_file = app_path('Transformers/StaffPeriodFeeTransformer.php');
        $insert_ref='\'water_fee\'=>$model->water_fee,';
        $this->insertFileWithCheck($trans_file,$insert_ref,['water_fee'=>$col]);

        //1.9 util get_fee_types
        $util_file = app_path('Helpers/Utils.php');
        if($hasMeter){
            $insert_ref = "(object)['id'=>'water_fee_type_id','type_name'=>'waterFeeType','model'=>'App\Models\WaterFeeType','name'=>'water_fee','cn_name'=>'水费','meter_type_id'=>1,'is_simple'=>true,'enable'=>true,'calc_method'=>'calcSimpleTypeConsumeMoney'],";
        }else{
            $insert_ref = "(object)['id'=>'water_fee_type_id','type_name'=>'waterFeeType','model'=>'App\Models\WaterFeeType','name'=>'water_fee','cn_name'=>'水费','meter_type_id'=>1,'is_simple'=>true,'enable'=>true,'calc_method'=>'calcSimpleTypeMoneyWithoutConsume'],";
        }
        $this->insertFileWithCheck($util_file,$insert_ref,['water_fee'=>$col,'WaterFeeType'=>$pascalType,'waterFeeType'=>$camelType,'水费'=>$feeTypeCn,'=>1'=>'=>'.optional($meter)->id]);


        //2.0 do migrate
        $this->call('migrate');

        //2.1 do perm gen and dispatch
        $this->call('perm:gen');

    }


    public function makeAddColumnMigration($table,$column,$type,$nullable=true){
        $name="alter_table_$table".'_add_'.$column;
        $pattern = database_path('migrations/').'*.php';
        $files = glob($pattern);
        $hasBuild = false;
        foreach ($files as $file){
            if(str_contains($file,$name)){
                $hasBuild = true;
                break;
            }
        }
        if(!$hasBuild){
            $this->call("make:migration",['name'=>$name,"--table"=>"$table"]);
            sleep(1);
            $new_migration = $this->findFileByName($pattern,$name);
            $this->info($new_migration);

            $insert = <<<'EOF'
            if(!Schema::hasColumn('[TABLE]','[COLUMN]')){
                $table->[TYPE]('[COLUMN]')->nullable();
            }
EOF;
            $insert = str_replace('[TABLE]',$table,$insert);
            $insert = str_replace('[COLUMN]',$column,$insert);
            $insert = str_replace('[TYPE]',$type,$insert);
            if(!$nullable){
                $insert = str_replace('->nullable()','',$insert);
            }
            $this->insert($new_migration,16,$insert,false);
            $idx = $this->indexOfLine($new_migration,'public function down()')+3;
            $this->insert($new_migration,$idx,'$'."table->dropColumn('$column');",false);
        }
    }

    public function replaceTextInFile($file,$search,$replace){
        file_put_contents($file,str_replace($search,$replace,file_get_contents($file)));
    }

    function find_last_modified_file(string $dir):string    {
        if (!is_dir($dir)) throw new \ValueError('Expecting a valid directory!');

        $latest = null;
        $latestTime = 0;
        foreach (scandir($dir) as $path) if (!in_array($path, ['.', '..'], true)) {
            $filename = $dir . DIRECTORY_SEPARATOR . $path;
            if (is_dir($filename)) {
                $directoryLastModifiedFile = find_last_modified_file($filename);

                if (null === $directoryLastModifiedFile) {
                    continue;
                } else {
                    $filename = $directoryLastModifiedFile;
                }
            }

            $lastModified = filemtime($filename);
            if ($lastModified > $latestTime) {
                $latestTime = $lastModified;
                $latest = $filename;
            }
        }
        return $latest;
    }

    function findFileByName($pattern, $name, $exactly=false){
        $files = glob($pattern);
        foreach ($files as $file){
            if($exactly){
                $splFile = new \SplFileInfo($file);
                if($splFile->getFilename()==$name){
                    return $file;
                }
            }else{
                if(str_contains($file,$name)){
                    return $file;
                }
            }

        }
    }

    function indexOfLine($file_path, $line){
        if(!$fileContent = @file($file_path)){
            $this->warn('文件不存在');
        }
        foreach ($fileContent as $i=>$l){
            if(trim($l)==$line){
                return $i;
            }
        }
        return -1;
    }

    function indexOfContainLine($file_path, $line){
        if(!$fileContent = @file($file_path)){
            $this->warn('文件不存在');
        }
        foreach ($fileContent as $i=>$l){
            $l = trim($l);
            if(str_contains($l,$line)){
                return $i;
            }
        }
        return -1;
    }

    function matchLines($file_path, $match_line){
        if(!$fileContent = @file($file_path)){
            $this->warn('文件不存在');
        }
        $arr=[];
        foreach ($fileContent as $i=>$l){
            $l = trim($l);
            if(str_contains($l,$match_line)){
                $arr[$i]=$l;
            }
        }
        return $arr;
    }

    /***
     * @param $file_path
     * @param $line_index
     * @param $insert_text
     * @param $confirm boolean
     */
    function insert($file_path, $line_index, $insert_text,$confirm=true){
        $this->info("going to insert $file_path");
        if($line_index<0){
            $this->info('插入索引不能小于0');
            return;
        }
        //@符号是差错控制操作者(又称“沉默”或“关闭”操作员)。它使PHP禁止由关联表达式生成的任何错误消息(注意、警告、致命等)。它的工作原理就像一个一元运算符，例如，它具有优先性和结合性。
        if(!$fileContent = @file($file_path)){
            $this->warn('文件不存在');
            return;
        }
        $lines_cnt = count($fileContent);
        if($line_index >= $lines_cnt) {
            $line_index = $lines_cnt;
        }
        $next_line=trim($fileContent[$line_index+1]);
        $start_line= trim($fileContent[$line_index]);
        $this->info("start line is：$start_line");
        $this->info("next line is：$next_line");
        if($confirm){
            $flag = $this->confirm("do you want to insert $file_path?");
            if($flag){
                $fileContent[$line_index].=$insert_text;
                $newContent = '';
                foreach($fileContent as $v){
                    $newContent.= $v;
                }
                if(!file_put_contents($file_path,$newContent)){
                    $this->warn('无法写入数据');
                }
                $this->info('成功写入文档' . $file_path);
            }else{
                $this->info('替换已取消');
            }
        }else{
            $fileContent[$line_index].=$insert_text."\n";
            $newContent = '';
            foreach($fileContent as $v){
                $newContent.= $v;
            }
            if(!file_put_contents($file_path,$newContent)){
                $this->warn('无法写入数据');
            }
            $this->info('成功写入文档' . $file_path);
        }
    }

    public function replaceLine($file_path,$line_index,$line){
        $this->info("going to insert $file_path");
        if($line_index<0){
            $this->info('插入索引不能小于0');
            return;
        }
        //@符号是差错控制操作者(又称“沉默”或“关闭”操作员)。它使PHP禁止由关联表达式生成的任何错误消息(注意、警告、致命等)。它的工作原理就像一个一元运算符，例如，它具有优先性和结合性。
        if(!$fileContent = @file($file_path)){
            $this->warn('文件不存在');
        }
        $lines_cnt = count($fileContent);
        if($line_index >= $lines_cnt) {
            $line_index = $lines_cnt;
        }
        $next_line=trim($fileContent[$line_index+1]);
        $start_line= trim($fileContent[$line_index]);
        $this->info("start line is：$start_line");
        $this->info("next line is：$next_line");

        $fileContent[$line_index]= $line;
        $newContent = '';
        foreach($fileContent as $v){
            $newContent.= $v;
        }
        if(!file_put_contents($file_path,$newContent)){
            $this->warn('无法写入数据');
        }
        $this->info('成功写入文档' . $file_path);

    }


    function copydir($strSrcDir, $strDstDir)
    {
        $dir = opendir($strSrcDir);
        if (!$dir) {
            return false;
        }
        if (!is_dir($strDstDir)) {
            if (!mkdir($strDstDir)) {
                return false;
            }
        }
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($strSrcDir . '/' . $file)) {
                    if (!copydir($strSrcDir . '/' . $file, $strDstDir . '/' . $file)) {
                        return false;
                    }
                } else {
                    if (!copy($strSrcDir . '/' . $file, $strDstDir . '/' . $file)) {
                        return false;
                    }
                }
            }
        }
        closedir($dir);
        return true;
    }

    /**
     * @param string $index_view
     * @param string $camelType
     * @param string $pascalType
     * @param $feeTypeCn
     * @param string $typeRoute
     */
    public function replaceViewsOnWaterFee(string $index_view, string $camelType, string $pascalType, $feeTypeCn, string $typeRoute)
    {
        $this->replaceTextInFile($index_view, 'waterFeeType', $camelType);
        $this->replaceTextInFile($index_view, 'WaterFeeType', $pascalType);
        $this->replaceTextInFile($index_view, '水费', $feeTypeCn);
        $this->replaceTextInFile($index_view, 'water-fee-types', $typeRoute);
    }

    public function replaceViewsOnManageFee(string $index_view, string $camelType, string $pascalType, $feeTypeCn, string $typeRoute)
    {
        $this->replaceTextInFile($index_view, 'manageFeeType', $camelType);
        $this->replaceTextInFile($index_view, 'ManageFeeType', $pascalType);
        $this->replaceTextInFile($index_view, '水费', $feeTypeCn);
        $this->replaceTextInFile($index_view, 'water-fee-types', $typeRoute);
    }

    public function replaceContent($file_src,$file_dist,array $replacements){
        $content = file_get_contents($file_src);
        foreach ($replacements as $from=>$to) {
            $content=str_replace($from,$to,$content);
        }
        file_put_contents($file_dist,$content);
    }

    public function replaceFileContent($file_path,array $replacements){
        $content = file_get_contents($file_path);
        foreach ($replacements as $from=>$to) {
            $content=str_replace($from,$to,$content);
        }
        file_put_contents($file_path,$content);
    }



    public function insertFileWithCheck(string $file_path,string $insert_ref,array $replacements,$idx_diff=0,$ref_line=null,$check_exist_line=null)
    {
        $i=0;
        $insert="";
        foreach ($replacements as $from=>$to) {
            if($i++==0){
                $insert = str_replace($from, $to, $insert_ref);
            }else{
                $insert = str_replace($from, $to, $insert);
            }

        }
        $ref_line = $ref_line?$ref_line:$insert_ref;
        if($check_exist_line){
            if($this->indexOfLine($file_path,$check_exist_line)==-1){
                $idx = $this->indexOfLine($file_path, $ref_line)+$idx_diff;
                $this->insert($file_path, $idx, $insert, false);
            }

        }else{
            $content = file_get_contents($file_path);
            if (!str_contains($content,$insert)) {
                $ref_line = $ref_line?$ref_line:$insert_ref;
                $idx = $this->indexOfLine($file_path, $ref_line)+$idx_diff;
                $this->insert($file_path, $idx, $insert, false);
            }
        }

    }


}
